<?php
    header("content-type:text/html;charset=utf-8");
    // $name = $_GET['username'];
    // $psw = $_GET['password'];
    $respArr = [];
    $link = mysql_connect('localhost', 'root', 'root') or die('数据链接失败');
    mysql_select_db('shop', $link);
    $userid = $_POST['userid'];
    $goodid = $_POST['goodid'];
    if(!$userid){
        $respArr['code'] = -1;
        $respArr['msg'] = '请传入用户id';
        echo json_encode($respArr);
        return;
    }
    /* 验证用户存不存在 */
    $sql = "select * from `user` where `id`= $userid";
    $res = mysql_query($sql);
    if(!$res || !mysql_fetch_assoc($res)){
        $respArr['code'] = -1;
        $respArr['msg'] = '用户不存在';
        echo json_encode($respArr);
        return;
    }
    if(!$goodid){
        $respArr['code'] = -1;
        $respArr['msg'] = '请传入商品id';
        echo json_encode($respArr);
        return;
    }
    /* 验证商品存不存在 */
    $sql = "select * from `goods` where id = $goodid";
    $res1 = mysql_query($sql);
     // 匹配就是$row就是一个resource
     // 匹配不上$row返回就是false boolean
    $arr = [];
    if($res1){
        while($row = mysql_fetch_assoc($res1)){
            array_push($arr,$row);
        }
    }
    if(count($arr)){
        $sql = "select * from `cart` where `good_id` = $goodid";
        $res=mysql_query($sql);
        $row = mysql_fetch_assoc($res);
        if($row){
            $respArr['code'] = 0;
            $respArr['msg'] = '购物车商品已存在';
        }else{
            $newArr = $arr[0];
            $goodName = $newArr["good_name"];
            $price = $newArr['price'];
            $sImg = $newArr['s_img'];
            $sql = "INSERT INTO `cart` (`good_id`,`user_id`,`good_name`,`good_price`,`good_img`) VALUES ($goodid, $userid, '$goodName', $price, '$sImg')";
            $res1 = mysql_query($sql);
            if($res1){
                $respArr['code'] = 1;
                $respArr['msg'] = '加入成功';
            }else{
                $respArr['code'] = 0;
                $respArr['msg'] = 'sql执行插入失败，无法加入购物车';
            }
        }
       
    }else{
        $respArr['code'] = 0;
        $respArr['msg'] = '商品不存在';
    }
    echo json_encode($respArr);
?>